package Back;

import java.util.Arrays;

/**
 * @author zhang kun
 * @Classname Solution
 * @Description TODO
 * @Date 2021/8/21 20:22
 */
public class Solution {
    public static void main(String[] args) {
        int[] array = {12,33,5,4,6,767,8,8,988};
        int[] topKFrequent = topKFrequent(array, 3);
        System.out.println(Arrays.toString(topKFrequent));
    }
    public static int[] topKFrequent(int[] nums, int k) {
        int[] array = new int[k];
        for(int i = 0;i<k;i++){
            array[i] = nums[i];
        }
        adjust(array,0,array.length);
        for(int i = k;i<nums.length;i++){
            if(nums[i] > array[0]){
                array[0] = nums[i];
                adjust(array,0,array.length);
            }
        }
        return array;
    }

    public static void adjust(int[] array,int begin,int end){
        int temp = array[begin];
        for(int i = begin*2+1;i<end;i++){
            if(i+1 < end && array[i] > array[i+1]){
                i++;
            }
            if(array[i] < temp){
                array[begin] = array[i];
                begin = i;
            }

        }
        array[begin] = temp;
    }
}
